<template>
  <div>
    <el-form
      :model="groupForm"
      :rules="rules"
      ref="GroupForm"
      label-width="80px"
    >
      <el-form-item
        label="群组名"
        prop="name"
      >
        <el-input
          placeholder="请输入群组名"
          v-model="groupForm.name"
        >
        </el-input>
      </el-form-item>
    </el-form>
    <form-button
      :loading="submitLoading"
      @submit="submitForm('GroupForm')"
      @click="cancelSubmit"
    />
  </div>
</template>

<script>
import { groupCreate } from '@/api/group'
export default {
  name: 'CreateGroupForm',
  data () {
    return {
      groupForm: {
        name: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入群组名', trigger: 'blur' },
          { max: 20, message: '长度最多20个字符', trigger: 'blur' }
        ]
      },
      submitLoading: false
    }
  },
  methods: {
    reset () {
      this.groupForm.name = ''
    },
    // 取消提交
    cancelSubmit () {
      this.$emit('cancel')
    },
    // 提交修改表单
    submitForm (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.handleGroupCreate()
        } else {
          return false
        }
      })
    },
    // 创建群组
    async handleGroupCreate () {
      try {
        this.submitLoading = true
        const { data } = await groupCreate(this.groupForm.name)
        this.submitLoading = false
        this.$emit('submit', data)
      } catch {
        this.submitLoading = false
      }
    }
  }
}
</script>
